package com.oscar.ehome.view.pageview;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hp.hpl.sparta.Text;
import com.oscar.ehome.R;
import com.oscar.ehome.base.C;
import com.oscar.ehome.base.activity.BasesActivity;
import com.oscar.ehome.bean.pagebean.AnnualIncome;
import com.oscar.ehome.bean.pagebean.BaoDanGeRenBean;
import com.oscar.ehome.bean.pagebean.BaoDanTiaoBean;
import com.oscar.ehome.bean.pagebean.MingpianBean;
import com.oscar.ehome.bean.pagebean.ShuJuHuixianBean;
import com.oscar.ehome.bean.pagebean.XuanXiangShuJuBean;
import com.oscar.ehome.bean.pagebean.mingpianjson;
import com.oscar.ehome.bean.setbean.FeedBackBean;
import com.oscar.ehome.bean.setbean.TokenBean;
import com.oscar.ehome.presenter.PagePresenter;
import com.oscar.ehome.provider.gildeimage.GildeUtils;
import com.oscar.ehome.utils.basethem.TintManager;
import com.oscar.ehome.utils.system.SystemConfigFactory;
import com.oscar.ehome.utils.upload.OnUploadListener;
import com.oscar.ehome.utils.upload.UploadUtil;
import com.oscar.ehome.utils.util.CommonUtils;
import com.oscar.ehome.utils.util.MyEditText;
import com.oscar.ehome.utils.util.ToastUtil;
import com.oscar.ehome.view.loginview.LoginActivity;
import com.oscar.ehome.view.pageview.view.BaoDanGeRenView;
import com.oscar.ehome.view.pageview.view.MingpianView;
import com.yanzhenjie.album.Album;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by juxing
 * author: SunHaoZhao
 * date: On 2018/3/27
 */

public class BaoDanGeRenInfoActivity extends BasesActivity<BaoDanGeRenView, PagePresenter> implements BaoDanGeRenView, View.OnClickListener {

    PagePresenter pagePresenter;


    String token = "";
    String str;
    @BindView(R.id.title_img_back)
    ImageView titleImgBack;
    @BindView(R.id.title_tv_menu)
    TextView titleTvMenu;
    @BindView(R.id.title_layout_left)
    RelativeLayout titleLayoutLeft;
    @BindView(R.id.title_topbar)
    TextView titleTopbar;
    @BindView(R.id.titlebar_img_right)
    ImageView titlebarImgRight;
    @BindView(R.id.title_img_right)
    ImageView titleImgRight;
    @BindView(R.id.home_tv_num)
    TextView homeTvNum;
    @BindView(R.id.right_layout)
    RelativeLayout rightLayout;
    @BindView(R.id.basetitle_bar)
    RelativeLayout basetitleBar;
    @BindView(R.id.ll_addViewone)
    LinearLayout addHotelNameView;
    @BindView(R.id.quesiton_tj)
    Button quesiton_tj;
    String jiatingid;
    String[] jiatingshuzu;
    String[] jiatingshuzuid;
    String[] jiatingfshouruidshuzuvalve;
    String[] hunyinshuzu = new String[2];
    String[] shebaoshuzu = new String[2];
    String[] xingbieshuzu = new String[2];



    Gson gson = new Gson();
    List<BaoDanGeRenBean> persons = new ArrayList<>();
    List<String> chengyuan = new ArrayList<>();

    String name;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.baodangerenxinxi);
        ButterKnife.bind(this);
        initView();
        //默认添加一个Item
        addViewItem();
    }

    @Override
    protected PagePresenter createPresenter() {
        pagePresenter = new PagePresenter(this);
        return pagePresenter;
    }

    public void initView() {
        CommonUtils.url_code = 0;
        hunyinshuzu[0] = "已婚";
        hunyinshuzu[1] = "未婚";
        shebaoshuzu[0] = "有";
        shebaoshuzu[1] = "无";

        xingbieshuzu[0] = "男";
        xingbieshuzu[1] = "女";
        Intent in = getIntent();
        jiatingid = in.getStringExtra("jiatingid");

        jiatingshuzuid = in.getStringArrayExtra("jiatingfshouruidshuzu");
        jiatingfshouruidshuzuvalve = in.getStringArrayExtra("jiatingfshouruidshuzuvalve");
        chengyuan = (List<String>) in.getSerializableExtra("beibaoxianrenjihe");

        jiatingshuzu = in.getStringArrayExtra("jiatingfshourushuzu");
        titleImgBack.setImageResource(R.mipmap.fanhui);

        titleTopbar.setText("填写被保险人信息");
        titleImgBack.setOnClickListener(this);
        token = SystemConfigFactory.getInstance(BaoDanGeRenInfoActivity.this).getSystemConfig().getToken();
        basetitleBar.setBackgroundColor(Color.parseColor(SystemConfigFactory.getInstance(BaoDanGeRenInfoActivity.this).getSystemConfig().getColor()));

        TintManager.setTint(quesiton_tj, Color.parseColor(SystemConfigFactory.getInstance(this).getSystemConfig().getColor()));
        quesiton_tj.setOnClickListener(this);
        pagePresenter.getbaodangerenshuju(token, jiatingid);


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.title_img_back:
                finish();
                break;
            case R.id.tianjiaimg://点击添加按钮就动态添加Item


                for (int i = 0; i < addHotelNameView.getChildCount(); i++) {
                    View childAt = addHotelNameView.getChildAt(i);
                    EditText xingming = childAt.findViewById(R.id.xingming);
                    TextView xingbie = childAt.findViewById(R.id.xingbie);
                    EditText nianling = childAt.findViewById(R.id.nianling);
                    EditText lianxifangshi = childAt.findViewById(R.id.lianxifangshi);
                    TextView jiatingnianshouru = childAt.findViewById(R.id.jiatingnianshouru);
                    TextView shebao = childAt.findViewById(R.id.shebao);
                    TextView hunyinzhuangkuang = childAt.findViewById(R.id.hunyinzhuangkuang);

                    if (!xingming.getText().toString().equals("")
                            && !xingbie.getText().toString().equals("")
                            && !nianling.getText().toString().equals("")
                            && !lianxifangshi.getText().toString().equals("")
                            && !shebao.getText().toString().equals("")
                            && !hunyinzhuangkuang.getText().toString().equals("")
                            && (!jiatingnianshouru.getText().toString().equals("") || i > 0)) {
                        if (i == addHotelNameView.getChildCount() - 1) {
                            addViewItem();
                            return;
                        }
                    } else {
                        ToastUtil.show(BaoDanGeRenInfoActivity.this, "您第" + (i + 1) + "组没有填写完整，请完善");
                    }

                }


                break;
            case R.id.quesiton_tj://打印数据
                SubmitFeedBack();

                break;
        }
    }

    private void SubmitFeedBack() {
        CommonUtils.url_code = 0;
        //判断为空

        for (int i = 0; i < addHotelNameView.getChildCount(); i++) {
            View childAt = addHotelNameView.getChildAt(i);
            EditText xingming = childAt.findViewById(R.id.xingming);
            TextView xingbie = childAt.findViewById(R.id.xingbie);
            EditText nianling = childAt.findViewById(R.id.nianling);
            EditText lianxifangshi = childAt.findViewById(R.id.lianxifangshi);
            EditText jiatingbeizhu = childAt.findViewById(R.id.jiatingbeizhu);
            TextView jiatingnianshouru = childAt.findViewById(R.id.jiatingnianshouru);
            TextView shebao = childAt.findViewById(R.id.shebao);
            TextView hunyinzhuangkuang = childAt.findViewById(R.id.hunyinzhuangkuang);


            if (!xingming.getText().toString().equals("")
                    && !xingbie.getText().toString().equals("")
                    && !nianling.getText().toString().equals("")
                    && !lianxifangshi.getText().toString().equals("")
                    && !shebao.getText().toString().equals("")
                    && !hunyinzhuangkuang.getText().toString().equals("")
                    && (!jiatingnianshouru.getText().toString().equals("") || i > 0)
                 ) {


                BaoDanGeRenBean p = new BaoDanGeRenBean();
                p.setAge(Integer.parseInt(nianling.getText().toString()));

                p.setFamilyId(jiatingid);
                if (i == 0) {
                    p.setIsOwner("1");
                } else {
                    p.setIsOwner("0");
                }
                if (hunyinzhuangkuang.getText().toString().equals("已婚")) {
                    p.setMaritalStatus("1");
                } else {
                    p.setMaritalStatus("0");
                }
                p.setMobile(lianxifangshi.getText().toString());
                p.setName(xingming.getText().toString());
                if (shebao.getText().toString().equals("有")) {
                    p.setSocialInsurance("1");
                } else {
                    p.setSocialInsurance("0");
                }
                if (!jiatingbeizhu.getText().toString().equals("")&&jiatingbeizhu.getText()!=null) {
                    p.setRemarks(jiatingbeizhu.getText().toString());
                } else {
                    p.setRemarks("");
                }
                AnnualIncome ss = new AnnualIncome();

                for (int j = 0; j < jiatingshuzu.length; j++) {
                    if (jiatingshuzu[j].equals(jiatingnianshouru.getText().toString())) {

                        ss.setValue(jiatingfshouruidshuzuvalve[j]);

                    } else {
                        continue;
                    }
                }


                p.setAnnualIncome(ss);

                if (xingbie.getText().toString().equals("男")) {
                    p.setSex("1");
                } else {
                    p.setSex("0");
                }
                persons.add(p);
                if (i == addHotelNameView.getChildCount() - 1) {

                    showLoading();
                     str = gson.toJson(persons);

                    zuihoujiancha();
                    persons.clear();
                }
            } else {
                persons.clear();
                ToastUtil.show(BaoDanGeRenInfoActivity.this, "您第" + (i + 1) + "组没有填写完整，请完善");
            }
        }

    }

    private void zuihoujiancha() {

        if(chengyuan.size()>0){
            for (int k = 0; k < chengyuan.size(); k++) {
                for (int j = 0; j < addHotelNameView.getChildCount(); j++) {
                    View childAt = addHotelNameView.getChildAt(j);
                    EditText xingming = childAt.findViewById(R.id.xingming);
                    if (chengyuan.get(k).toString().equals(xingming.getText().toString())) {
                        break;
                    }else{
                        if(j==addHotelNameView.getChildCount()-1){
                            str="";
                            ToastUtil.show(BaoDanGeRenInfoActivity.this,"您还需要填写"+chengyuan.get(k)+"的信息。");
                            dismissLoading();
                            return;
                        }
                    }
                }
                if(k==chengyuan.size()-1){

                    pagePresenter.subbaodangereninfo(token, str, jiatingid);
                    dismissLoading();
                    ToastUtil.show(BaoDanGeRenInfoActivity.this,"正在提交，请稍候");
                }
            }
        }else{
            pagePresenter.subbaodangereninfo(token, str, jiatingid);
            dismissLoading();
            ToastUtil.show(BaoDanGeRenInfoActivity.this,"正在提交，请稍候");

        }

    }

    /**
     * Item排序
     */
    private void sortHotelViewItem() {
        //获取LinearLayout里面所有的view
        for (int i = 0; i < addHotelNameView.getChildCount(); i++) {
            final View childAt = addHotelNameView.getChildAt(i);
            final ImageView btn_remove = childAt.findViewById(R.id.shanchuimg);
            final TextView shebao = childAt.findViewById(R.id.shebao);
            final TextView hunyinzhuangkuang = childAt.findViewById(R.id.hunyinzhuangkuang);
            final TextView jiatingnianshouru = childAt.findViewById(R.id.jiatingnianshouru);
            final TextView xingbie = childAt.findViewById(R.id.xingbie);
            btn_remove.setTag("remove");//设置删除标记

            btn_remove.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //从LinearLayout容器中删除当前点击到的ViewItem
                    if (addHotelNameView.getChildCount() > 1) {
                        addHotelNameView.removeView(childAt);
                        sortHotelViewItem();
                    } else {
                        ToastUtil.show(BaoDanGeRenInfoActivity.this, "仅剩一组，无法删除");
                    }

                }
            });
            xingbie.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    tankuangfanhui(xingbieshuzu, xingbie);

                }
            });
            shebao.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    tankuangfanhui(shebaoshuzu, shebao);

                }
            });
            hunyinzhuangkuang.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    tankuangfanhui(hunyinshuzu, hunyinzhuangkuang);

                }
            });
            jiatingnianshouru.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    tankuangfanhui(jiatingshuzu, jiatingnianshouru);
                }
            });

            //如果是最后一个ViewItem，就设置为添加
            if (i == (addHotelNameView.getChildCount() - 1)) {
                LinearLayout btn_add = childAt.findViewById(R.id.tianjiaimg);
                btn_add.setVisibility(View.VISIBLE);
                btn_add.setTag("add");
                btn_add.setOnClickListener(this);

            } else {
                LinearLayout btn_add = childAt.findViewById(R.id.tianjiaimg);
                btn_add.setVisibility(View.GONE);

            }
        }
    }

    private void tankuangfanhui(String[] shuzu, final TextView v) {

        AlertDialog.Builder builder = new AlertDialog.Builder(BaoDanGeRenInfoActivity.this);
        builder.setSingleChoiceItems(shuzu, 0, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                ListView lw = ((AlertDialog) dialog).getListView();
                Object checkedItem = lw.getAdapter().getItem(which);


                dialog.dismiss();
                v.setText((String) checkedItem);


            }
        });
        AlertDialog dialog = builder.create();
        dialog.show();


    }

    //添加ViewItem
    private void addViewItem() {
        if (addHotelNameView.getChildCount() == 0) {//如果一个都没有，就添加一个
            View hotelEvaluateView = View.inflate(this, R.layout.baodangerenxinxiitem, null);
            LinearLayout btn_add = hotelEvaluateView.findViewById(R.id.tianjiaimg);
            LinearLayout nianshouru = hotelEvaluateView.findViewById(R.id.nianshouruyincang);
            LinearLayout jiatingbeizhuyincang = hotelEvaluateView.findViewById(R.id.beizhuyincang);
            jiatingbeizhuyincang.setVisibility(View.VISIBLE);
            nianshouru.setVisibility(View.VISIBLE);
            btn_add.setVisibility(View.VISIBLE);
            btn_add.setTag("add");
            btn_add.setOnClickListener(this);
            addHotelNameView.addView(hotelEvaluateView);
            sortHotelViewItem();
        } else {//如果有一个以上的Item,点击为添加的Item则添加
            View hotelEvaluateView = View.inflate(this, R.layout.baodangerenxinxiitem, null);
            LinearLayout nianshouru = hotelEvaluateView.findViewById(R.id.nianshouruyincang);
            LinearLayout jiatingbeizhuyincang = hotelEvaluateView.findViewById(R.id.beizhuyincang);
            nianshouru.setVisibility(View.GONE);
            jiatingbeizhuyincang.setVisibility(View.GONE);
            addHotelNameView.addView(hotelEvaluateView);
            sortHotelViewItem();


        }

    }



    @Override
    public void subbaodanshuju(String result) {
        if (result.equals("成功")) {
            dismissLoading();
            Intent in = new Intent();
            in.putExtra("contentsrc", "/app/policysheet/policySheet/loadPolicySheetAnalysis/" + jiatingid);

            in.putExtra("type", "baodan");
            in.putExtra("id", jiatingid);
            in.putExtra("name", "保单分析");

            in.setClass(BaoDanGeRenInfoActivity.this, BannerWebActivity.class);
            startActivity(in);
            finish();
        }

    }

    @Override
    public void getbaodangerenyiyoushuju(ShuJuHuixianBean result) {
        if (result.getObject() != null) {
            java.lang.reflect.Type listType = new TypeToken<ArrayList<BaoDanGeRenBean>>() {
            }.getType();//TypeToken内的泛型就是Json数据中的类型
            ArrayList<BaoDanGeRenBean> books = gson.fromJson(gson.toJson(result.getObject()), listType);
            for (int i = 0; i < books.size(); i++) {

                if (i > 0) {
                    addViewItem();

                }

                View childAt = addHotelNameView.getChildAt(i);
                EditText xingming = childAt.findViewById(R.id.xingming);
                TextView xingbie = childAt.findViewById(R.id.xingbie);
                EditText nianling = childAt.findViewById(R.id.nianling);
                EditText lianxifangshi = childAt.findViewById(R.id.lianxifangshi);
                EditText jiatingbeizhu = childAt.findViewById(R.id.jiatingbeizhu);
                TextView jiatingnianshouru = childAt.findViewById(R.id.jiatingnianshouru);
                TextView shebao = childAt.findViewById(R.id.shebao);
                TextView hunyinzhuangkuang = childAt.findViewById(R.id.hunyinzhuangkuang);

                xingming.setText(books.get(i).getName());
                if (books.get(i).getRemarks() != null && !books.get(i).getRemarks().equals("")) {
                    jiatingbeizhu.setText(books.get(i).getRemarks());
                }
                if (books.get(i).getSex().equals("0")) {
                    xingbie.setText("女");
                } else {
                    xingbie.setText("男");
                }
                nianling.setText(books.get(i).getAge() + "");
                lianxifangshi.setText(books.get(i).getMobile() + "");
                if(i==0){
                    jiatingnianshouru.setText(books.get(i).getAnnualIncome().getLabel());
                }else{
                }

                if (books.get(i).getSocialInsurance().equals("1")) {
                    shebao.setText("有");
                } else {
                    shebao.setText("无");
                }
                if (books.get(i).getMaritalStatus().equals("1")) {
                    hunyinzhuangkuang.setText("已婚");
                } else {
                    hunyinzhuangkuang.setText("未婚");
                }
            }


        }


    }

    @Override
    public void erroy() {

    }

    @Override
    public void erry(String result) {
        dismissLoading();
        if (result.equals("tiaoguo")) {
        } else {
            Toast.makeText(BaoDanGeRenInfoActivity.this, result, Toast.LENGTH_SHORT).show();
        }
        if (result.contains("过期")) {
            getSharedPreferences("appbase", Context.MODE_PRIVATE).edit().clear().commit();
            SystemConfigFactory.getInstance(BaoDanGeRenInfoActivity.this).getSystemConfig().SetLogin(false);
            SystemConfigFactory.getInstance(this).getSystemConfig().setIsFirst(true);
            Intent intent = new Intent(BaoDanGeRenInfoActivity.this, LoginActivity.class);
            startActivity(intent);
            finish();
        }
    }


}
